# -!- coding: utf-8 -!-
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：get_stock_index.py
#日期：2019-01-10
#备注：获取东方财富网的沪深重要指数:http://quote.eastmoney.com/centerv2/hszs,存入到数据库，indexInfo_to_mysql()    
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

import requests
import time
from datetime import datetime

from pacong.stock.stock_config import db,cursor,headers
from pycacho.cachobase.logger import Logger

logger = Logger("get_stock_index").get_log()


def createTable():
    sql1 = 'drop table if exists stock_index;'
    sql2 = 'CREATE TABLE stock_index (index_type int,index_no varchar(20),index_name varchar(20),index_newPrice float,index_change float,index_changeRate float,index_volume float,index_turnover float,index_yesterdayPrice float,index_todayPrice float,index_maxPrice float,index_minPrice float,index_date varchar(20),' \
           'PRIMARY KEY (index_no,index_date));'           # 沪深重要指数

    cursor.execute(sql1)
    cursor.execute(sql2)
    db.commit()


# 沪深重要指数
def indexInfo_to_mysql(index_type,index_no,index_name,index_newPrice,index_change,index_changeRate,index_volume,index_turnover,index_yesterdayPrice,index_todayPrice,index_maxPrice,index_minPrice,index_date,f_c):
    sql = "insert into stock_index (index_type,index_no,index_name,index_newPrice,index_change,index_changeRate,index_volume,index_turnover,index_yesterdayPrice,index_todayPrice,index_maxPrice,index_minPrice,index_date,f_c) " \
          "values ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s');" \
          % (index_type,index_no,index_name,index_newPrice,index_change,index_changeRate,index_volume,index_turnover,index_yesterdayPrice,index_todayPrice,index_maxPrice,index_minPrice,index_date,f_c)
    try:
        cursor.execute(sql)
    except Exception as e:
        # 发生错误时回滚
        db.rollback()
        print(str(e))
    else:
        db.commit()
        logger.info('事务处理成功')


# 获取沪深重要指数信息
def get_stock():
    url = 'http://70.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=50&fltt=2&fid=&fs=b:MK0010&' \
          'fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f26,f22,f11,f62,f128,f136,f115,f152'
    resp = requests.get(url, headers=headers)
    data = resp.json()['data']
    total_num = data['total']
    #print('指数总指数个数：',total_num)
    #print(data)
    index_info = []
    index_info.append(data['diff']['0'])       # 上证指数
    index_info.append(data['diff']['1'])       # 深证成指
    index_info.append(data['diff']['2'])       # 沪深300
    index_info.append(data['diff']['3'])       # 中小板指
    index_info.append(data['diff']['4'])       # 创业板指
    index_info.append(data['diff']['6'])       # 上证50
    for index in index_info:
        #print(index)
        index_type = index['f13']              # 指数类型 1-沪市，0-深市
        index_no = index['f12']                # 指数代码
        index_name = index['f14']              # 指数名称
        index_newPrice = index['f2']           # 最新价
        index_change = index['f4']             # 涨跌额
        index_changeRate = index['f3']         # 涨跌幅
        index_volume = index['f5']             # 成交量
        index_turnover = index['f6']           # 成交额
        index_yesterdayPrice = index['f18']    # 昨收
        index_todayPrice = index['f17']        # 今开 最高
        index_maxPrice = index['f15']          # 最高
        index_minPrice = index['f16']          # 最低
        index_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        f_c = index_turnover/data['diff']['4']['f6']
        print(index_type, index_no, index_name, index_newPrice, index_change, index_changeRate,
                           index_volume, index_turnover,
                           index_yesterdayPrice, index_todayPrice, index_maxPrice, index_minPrice, index_date,f_c)


if __name__ == '__main__':
    #createTable()
    get_stock()
    time.sleep(5)